package dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import entity.GoodsClass;
import tools.DBTools;

public class GoodClassDao {

	//获取一级分类
	public List<GoodsClass> getGoodsOneClass() {
		 Connection conn = DBTools.getInstance().getConnection();
		List<GoodsClass> classList = new ArrayList<>();
		String sql = "select * from TBL_GOOD_CLASS where CLASS_FATHER = 0";
		PreparedStatement ps = null;
		ResultSet rs = null;
		try {
			ps = conn.prepareStatement(sql);
			rs = ps.executeQuery();
			while(rs.next()) {
				GoodsClass goodClass = new GoodsClass(rs.getInt("CLASS_ID"), 
						rs.getString("CLASS_NAME"), rs.getInt("CLASS_FATHER"));
				classList.add(goodClass);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			DBTools.getInstance().closeConnection(conn, ps, rs);
		}
		return classList;
	}
	
	//根据一级class获取二级class
	public List<GoodsClass> getGoodsTwoClass(int oneClassId) {
		 Connection conn = DBTools.getInstance().getConnection();
		 List<GoodsClass> twoGoodList = new ArrayList<>();
		String sql = "select * from TBL_GOOD_CLASS where CLASS_FATHER = ?";
		PreparedStatement ps = null;
		ResultSet rs = null;
		try {
			ps = conn.prepareStatement(sql);
			ps.setInt(1, oneClassId);
			rs = ps.executeQuery();
			while(rs.next()) {
				GoodsClass goodClass = new GoodsClass(rs.getInt("CLASS_ID"),
						rs.getString("CLASS_NAME"), rs.getInt("CLASS_FATHER"));
				twoGoodList.add(goodClass);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			DBTools.getInstance().closeConnection(conn, ps, rs);
		}
		return twoGoodList;
	}
	
	//获取商品类别对象通过id
	public GoodsClass getClassById(int classId) {
		Connection conn = DBTools.getInstance().getConnection();
		GoodsClass goodClass = null;
		String sql = "select * from TBL_GOOD_CLASS where CLASS_ID = ?";
		PreparedStatement ps = null;
		ResultSet rs = null;
		try {
			ps = conn.prepareStatement(sql);
			ps.setInt(1, classId);
			rs = ps.executeQuery();
			rs.next();
			goodClass = new GoodsClass(rs.getInt("CLASS_ID"), 
					rs.getString("CLASS_NAME"), rs.getInt("CLASS_FATHER"));
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			DBTools.getInstance().closeConnection(conn, ps, rs);
		}
		return goodClass;
	}
	
	//测试
	public static void main(String[] args) {
		GoodClassDao gcDao = new GoodClassDao();
		List<GoodsClass> goodsOneClass = gcDao.getGoodsOneClass();
		System.out.println(goodsOneClass.toString());
	}
}
